package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.LinkedProblem;

import java.util.HashMap;

/**
 * On时间 O1空间
 *
 * @author tzp
 * @since 2020/10/20
 */
public class LC138_2 implements LinkedProblem {
    static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    //On时间 O1空间
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Node cur = head, newHead = new Node(head.val),
                newCur = newHead, dummy = new Node(-1);
        HashMap<Node, Node> map = new HashMap<>();
        while (cur != null) {
            map.put(cur, newCur);
            //完善newCur
            if (cur.next != null) {
                newCur.next = new Node(cur.next.val);
            }
            if (cur.random != null) {
                if (!map.containsKey(cur.random)) {
                    newCur.random = dummy;
                } else {
                    newCur.random = map.get(cur.random);
                }
            }
            cur = cur.next;
            newCur = newCur.next;
        }
        return newHead;
    }

    //[[7,null],[13,0],[11,4],[10,2],[1,0]]
    public static void main(String[] args) {
        System.out.println(new LC138_2());
    }
}
